package org.geektimes.projects.user.validation;

import org.geektimes.projects.user.domain.User;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class BeanValidationDemo {

    public static void main(String[] args) {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        // cache the factory somewhere
        Validator validator = factory.getValidator();

        User user = new User();
        user.setName("1111");
        user.setPassword("**1*");

        // 校验结果
        Set<ConstraintViolation<User>> violations = validator.validate(user);
        System.out.println(validateEntity(user));

        violations.forEach(c -> {
            System.out.println(c.getMessage());
        });
    }

    public static String validateEntity (User user) {
        Map<String, String> errorMap = new HashMap<>();
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        // cache the factory somewhere
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<User>> violations = validator.validate(user);
        violations.forEach(c -> errorMap.put(c.getPropertyPath().toString(), c.getMessage()));
        if (errorMap.size() > 0)
            return errorMap.toString();
        return null;
    }
}
